<template>
    <el-dialog v-model="show" title="对账" width="20%" align-center @close="handleClose">
        <el-form ref="formRef" :model="form" label-width="120px">
            <el-form-item label="对账日期：">
                {{ dateTime }}
            </el-form-item>
            <el-form-item label="供应商：">
                {{ props.initList.supplyName }}
            </el-form-item>
            <el-form-item label="入库金额：">
                {{ props.initList.inAmount }}
            </el-form-item>
            <!-- <el-form-item label="运费金额：" prop="freight">
                <el-input v-model="form.freight" placeholder="请输入" />
            </el-form-item> -->
            <el-form-item label="对账金额：" prop="reconciliationAmount" :rules="[
                { required: true, message: '请输入对账金额' },
                { validator: validateNumber, trigger: 'blur' }
            ]">
                <el-input v-model="form.reconciliationAmount" placeholder="请输入" />
            </el-form-item>
            <el-form-item label="对账备注：" prop="reconciliationRemark">
                <el-input v-model="form.reconciliationRemark" placeholder="请输入" />      
            </el-form-item>
        </el-form>

        <template #footer>
            <div class="dialog-footer">
                <el-button @click="handleClose">取 消</el-button>
                <el-button type="primary" @click="handleSubmit(formRef)">保 存</el-button>
            </div>
        </template>
    </el-dialog>
</template>

<script setup lang="ts">
import type { ComponentSize, FormInstance, FormRules } from 'element-plus'
import { updatePaperPurchaseOrderReconciliationApi } from '@/api/sj/purchaseManagement/paperProcurement/index';


const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const props = defineProps(['visible', 'initList']);
const emits = defineEmits(['submit', 'close']);

const show = ref(false);

watch(() => props.visible, async (newValue) => {
    show.value = newValue
    if (newValue) {
    }
}, { deep: true });

const formRef = ref();
const form = reactive({
    reconciliationAmount: '',
    reconciliationRemark: '',
});
const dateTime = ref('');


const validateNumber = (rule: any, value: any, callback: any) => {
    if (!value) {
        return callback();
    }
    const regex = /^\d+(\.\d+)?$/; // 允许任意位数的小数
    if (!regex.test(value)) {
        return callback(new Error('请输入有效的数字'));
    }
    callback();
};

const handleSubmit = async (formEl: FormInstance | undefined) => {
    if (!formEl) return
    await formEl.validate(async (valid, fields) => {
        if (valid) {

            if (Number(form.reconciliationAmount) == Number(props.initList.inAmount)) { 
                handleReconciliation()
            } else {
                const num = Number(form.reconciliationAmount) - Number(props.initList.inAmount);
                const msg = `实际对账金额${num > 0 ? '多' : '少'}于入库金额，${num > 0 ? '多' : '少'}了${num > 0 ? num : -num}元，您确定保存吗？`;
                ElMessageBox.confirm(msg, '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                })
                    .then(() => {
                        handleReconciliation()
                    })
                    .catch(() => { });
            }
            console.log('submit!')
        } else {
            console.log('error submit!', fields)
        }
    })
}

const handleReconciliation = async () => {         
    const query = {
        id: props.initList.id,
        supplyId: props.initList.supplyId,
        companyId: props.initList.companyId,
        ...form
    };

    try {
        const { code } = await updatePaperPurchaseOrderReconciliationApi(query);

        if (code == 200) {
            proxy?.$modal.msgSuccess('操作成功');
            emits('submit', true);

            handleClose();
        }
    } catch (error) {

    }
};


const handleClose = () => {
    formRef.value?.resetFields();
    emits('close');
};

onMounted(() => {
    const date = new Date();
    const year = date.getFullYear();
    const month = String(date.getMonth() + 1).padStart(2, '0'); // 月份从0开始，需要加1，并补零
    const day = String(date.getDate()).padStart(2, '0'); // 补零
    dateTime.value = `${year}-${month}-${day}`;
})
</script>

<style lang="scss" scoped></style>